package com.example.zhu95.mytimber.listener;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.zhu95.mytimber.MyApplication;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.activity.BaseActivity;
import com.example.zhu95.mytimber.activity.MainActivity;
import com.example.zhu95.mytimber.entity.PlayListBean;
import com.example.zhu95.mytimber.entity.PlayQueueRecord;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.utils.DBHelper;
import com.example.zhu95.mytimber.utils.PlaylistUtils;
import com.example.zhu95.mytimber.utils.Util;

import org.litepal.crud.DataSupport;

import java.util.List;

import static com.example.zhu95.mytimber.ConstantValue.PLAYMODE_SEQUENCE;
import static com.example.zhu95.mytimber.ConstantValue.PlayMusicCmd_Play;

/**
 * @author zhu95
 * @date 2018/3/28 23:35
 */
public class PopupMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
    protected BaseActivity activity;
    protected int songid;
    protected String songids;
    protected RecyclerView.Adapter adapter;

    public PopupMenuItemClickListener(BaseActivity activity, int songid, String songids, RecyclerView.Adapter adapter) {
        this.activity = activity;
        this.songid = songid;
        this.songids = songids;
        this.adapter = adapter;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        SongBean song = SongData.findSongByID(songid);
        switch (item.getItemId()) {
            case R.id.song_play:
                MyApplication.sendPlayMusicCmdBroadcast(songid, songids, PlayMusicCmd_Play);
                break;
            case R.id.song_play_next:
                playNext();
                break;
            case R.id.song_add2queue:
                boolean b = DBHelper.add2playqueue(songid);
                if (b) {
                    Toast.makeText(activity, R.string.add_song2playqueue_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, R.string.add_song2playqueue_failure, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.song_add2playlist:
                songAdd2Playlist();
                break;
            case R.id.song_go_album:
                if (activity instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) activity;
                    mainActivity.getAlbumClickListener().clickAlbum(song.getAlbumId());
                } else {
                    Intent intent = new Intent(activity, MainActivity.class);
                    intent.putExtra(activity.getString(R.string.go_album), song.getArtistId());
                    activity.startActivity(intent);
                }
                break;
            case R.id.song_go_artist:
                if (activity instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) activity;
                    mainActivity.getArtistClickListener().clickArtist(song.getArtistId());
                } else {
                    Intent intent = new Intent(activity, MainActivity.class);
                    intent.putExtra(activity.getString(R.string.go_artist), song.getArtistId());
                    activity.startActivity(intent);
                }
                break;
            case R.id.song_share:
                String path = song.getPath();
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("audio/mpeg");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
                activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.share)));
                break;
            case R.id.song_delete:
                //region song_delete
                new MaterialDialog.Builder(activity)
                        .title(R.string.delete_song)
                        .content(activity.getString(R.string.sure_delete_song, song.getTitle()))
                        .positiveText(R.string.delete)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog
                                                        dialog, @NonNull DialogAction which) {
                                boolean delete = DBHelper.deleteSong(songid);
                                if (delete) {
                                    adapter.notifyDataSetChanged();
                                    Toast.makeText(activity, R.string.delete_song_success, Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(activity, R.string.delete_failure, Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .negativeText(android.R.string.cancel).
                        show();
                //endregion
                break;
            default:
        }
        return false;
    }

    private void playNext() {
        try {
            // 如果添加的歌曲是当前播放的歌曲
            if (songid == BaseActivity.songid) {
                return;
            }
            List<PlayQueueRecord> all = DataSupport.findAll(PlayQueueRecord.class);
            if (all != null && all.size() > 0) {
                PlayQueueRecord playQueueRecord = all.get(0);
                if (playQueueRecord != null) {
                    String songids = playQueueRecord.getSongids();
                    String s = Util.INSTANCE.removeSongidFromSongids(songid, songids);
                    String songidStr = String.valueOf(BaseActivity.songid);
                    int i = s.indexOf(songidStr);
                    int position = i + songidStr.length();
                    String sb = s.substring(0, position) + "$" + songid +
                            s.substring(position, s.length());
                    playQueueRecord.setSongids(sb);
                    playQueueRecord.setPlayMode(PLAYMODE_SEQUENCE);
                    playQueueRecord.save();
                    Toast.makeText(activity, R.string.song_play_next_success, Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void songAdd2Playlist() {
        List<PlayListBean> playlists = PlaylistUtils.INSTANCE.getUserAddLists();
        String[] playlistTitles = new String[playlists.size() + 1];
        //数组的第一位是创建播放列表 后面是用户已创建的播放列表
        playlistTitles[0] = activity.getString(R.string.create_playlist);
        for (int i = 0; i < playlists.size(); i++) {
            playlistTitles[i + 1] = playlists.get(i).getTitle();
        }
        // region 选择需要添加的播放列表
        new MaterialDialog.Builder(activity)
                .title(R.string.add2playlist)
                .items(playlistTitles)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                        if (position == 0) {
                            createPlaylistAdd();
                        } else {
                            //add song to list
                            boolean isSuccess = PlaylistUtils.INSTANCE.addSong2Playlist(songid, text.toString());
                            if (isSuccess) {
                                Toast.makeText(activity, R.string.add_song2playlist_success, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    private void createPlaylistAdd() {
                        new MaterialDialog.Builder(activity)
                                .input(R.string.enter_playlist_name, R.string.empty_str, new MaterialDialog.InputCallback() {
                                    @Override
                                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                        boolean isSuccess = PlaylistUtils.INSTANCE.createPlaylist(input.toString());
                                        if (!isSuccess) {
                                            Toast.makeText(activity, R.string.create_playlist_error, Toast.LENGTH_SHORT).show();
                                        } else {
                                            //创建播放列表成功，将歌曲加入列表
                                            boolean isSuccessed = PlaylistUtils.INSTANCE.addSong2Playlist(songid, input.toString());
                                            if (isSuccessed) {
                                                Toast.makeText(activity, R.string.add_song2playlist_success, Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }
                                })
                                .positiveText(android.R.string.ok)
                                .negativeText(android.R.string.cancel).show();
                    }
                })
                .show();
        // endregion
    }
}
